import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FileRWDemo(),
    );
  }
}

// 读取文件的操作都是异步，返回Future对象
class FileRWDemo extends StatefulWidget {
  @override
  _FileRWDemoState createState() => _FileRWDemoState();
}

class _FileRWDemoState extends State<FileRWDemo> {
  int _counter;

  // 获取本地文件,即自定义counter.dat文件
  Future<File> _getLocalFile() async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    return File('$dir/counter.dat');
  }

  // 读取已保存的数据
  Future<int> _readCounter() async {
    try {
      File file = await _getLocalFile();
      String content = await file.readAsString();
      return int.parse(content);
    } on FileSystemException {
      return 0;
    }
  }

  // 写入文件
  Future<Null> _writeCounter(String counter) async {
    try {
      File file = await _getLocalFile();
      await file.writeAsString(counter);
    } on FileSystemException {}
  }

  // 增加计数
  Future<Null> _incrementCounter() async {
    setState(() {
      _counter++;
    });
    await _writeCounter(_counter.toString());
  }

  @override
  void initState() {
    super.initState();
    // 从本地文件读取数据
    _readCounter().then((value) {
      setState(() {
        _counter = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('数据持久化：本地文件'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _incrementCounter,
      ),
      body: Column(
        children: [
          Center(
            child: Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline3,
            ),
          ),
          Text('缓存目录:${getTemporaryDirectory()}'),
          Text('内存卡:${getExternalCacheDirectories()}'), // iOS不支持，直接报错
        ],
      ),
    );
  }
}
